package com.xja.shoppingmall.comfig;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.cloud.gateway.route.RouteDefinitionWriter;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * @author CHENCHEN
 * @title  事件推送Aware: 动态更新路由网关
 * @createTime 2021-12-1110:54
 */
@Slf4j
@Service
public class DynamicRouteServiceImpl implements ApplicationEventPublisherAware {

    //写路由定义
    private final RouteDefinitionWriter routeDefinitionWriter;

    //获取路由定义
    private final RouteDefinitionLocator routeDefinitionLocator;

    //事件发布
    private ApplicationEventPublisher publisher;

    public DynamicRouteServiceImpl(RouteDefinitionWriter routeDefinitionWriter, RouteDefinitionLocator routeDefinitionLocator) {
        this.routeDefinitionWriter = routeDefinitionWriter;
        this.routeDefinitionLocator = routeDefinitionLocator;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        //完成事件推送句柄的初始化
        this.publisher = applicationEventPublisher;
    }

    /**
     * 新增路由配置
     * @param definition
     * @return
     */
    public String addRouteDefinition(RouteDefinition definition){
        log.info("gateway add route : [{}]", definition);
        //保存路由配置并发布
        routeDefinitionWriter.save(Mono.just(definition)).subscribe();
        //发布事件通知给Gateway，同步新增的路由定义
        this.publisher.publishEvent(new RefreshRoutesEvent(this));

        return "success";
    }

    /**
     * 通过ID删除路由配置
     * @param id
     * @return
     */
    private String deleteById(String id){
        try{
            log.info("gateway delete rout id : [{}]", id);
            this.routeDefinitionWriter.delete(Mono.just(id)).subscribe();
            this.publisher.publishEvent(new RefreshRoutesEvent(this));
            return "success";
        }catch (Exception e){
            log.error("gateway delete route fail : [{}]", e.getMessage(), e);
            return "delete fail";
        }
    }

    /**
     * 更新路由配置
     * @param definition
     * @return
     */
    private String updateByRouteDefinition(RouteDefinition definition){
        try{
            log.info("gateway update route , delete: [{}]", definition);
            this.deleteById(definition.getId());
        }catch (Exception e){
            return "gateway update fail, not find route routeId : " + definition.getId();
        }

        try{
            log.info("gateway update route , save : [{}]", definition);
            this.addRouteDefinition(definition);
            this.publisher.publishEvent((new RefreshRoutesEvent(this)));
            return "success";
        }catch (Exception e){
            return "update route fail: ";
        }
    }

    /**
     * 批量更新路由到Gateway中
     * @param definitions
     * @return
     */
    public String updateList(List<RouteDefinition> definitions){
        log.info("gateway updates route : [{}]", definitions);
        //先拿到当前Gateway中存储的路由定义
        List<RouteDefinition> routeDefinitions = routeDefinitionLocator.getRouteDefinitions().buffer().blockFirst();
        if(!CollectionUtils.isEmpty(routeDefinitions)){
            //调用更新方法将自定义路由同步到Gateway中
            definitions.forEach(definition -> this.updateByRouteDefinition(definition));
        }
        return "success";
    }
}
